package com.qzsoft.zhjd.exp.modules.platformlaboratorydatas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.zhjd.common.utils.CommonConstants;
import com.qzsoft.zhjd.common.utils.StringUtils;
import com.qzsoft.zhjd.exp.modules.asphaltrequires.dto.AsphaltRequiresAndRefDto;
import com.qzsoft.zhjd.exp.modules.asphaltrequires.service.AsphaltRequiresRefService;
import com.qzsoft.zhjd.exp.modules.laboratorydevice.entity.LaboratoryDeviceEntity;
import com.qzsoft.zhjd.exp.modules.laboratorydevice.service.LaboratoryDeviceService;
//import com.qzsoft.zhjd.exp.modules.laboratoryductility.entity.LaboratoryDuctilityEntity;
//import com.qzsoft.zhjd.exp.modules.laboratoryductility.mapper.LaboratoryDuctilityMapper;
import com.qzsoft.zhjd.exp.modules.laboratorypenetration.entity.LaboratoryPenetrationEntity;
import com.qzsoft.zhjd.exp.modules.laboratorypenetration.mapper.LaboratoryPenetrationMapper;
import com.qzsoft.zhjd.exp.modules.laboratorysofteningpoint.entity.LaboratorySofteningPointEntity;
import com.qzsoft.zhjd.exp.modules.laboratorysofteningpoint.mapper.LaboratorySofteningPointMapper;
import com.qzsoft.zhjd.exp.modules.marshallrequires.entity.MarshallRequiresEntity;
import com.qzsoft.zhjd.exp.modules.marshallrequires.service.MarshallRequiresService;
import com.qzsoft.zhjd.exp.modules.marshallstability.entity.MarshallStabilityEntity;
import com.qzsoft.zhjd.exp.modules.marshallstability.mapper.MarshallStabilityMapper;
import com.qzsoft.zhjd.exp.modules.platformlaboratorydatas.constants.PlatformEnums;
import com.qzsoft.zhjd.exp.modules.platformlaboratorydatas.entity.PlatformLaboratoryDataEntity;
import com.qzsoft.zhjd.exp.modules.platformlaboratorydatas.mapper.PlatformLaboratoryDataMapper;
import com.qzsoft.zhjd.exp.modules.platformlaboratorydatas.service.PlatformLaboratoryDataService;
import org.apache.shiro.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * @Title: save
 * @Description: 沥青实验数据
 * @return Result 沥青实验数据
 */
@Service
public class PlatformLaboratoryDataServiceImpl extends ServiceImpl<PlatformLaboratoryDataMapper, PlatformLaboratoryDataEntity> implements PlatformLaboratoryDataService {
    @Autowired
    private AsphaltRequiresRefService requiresRefService;

    @Autowired
    private MarshallRequiresService marshallRequiresService;

    @Autowired
    private LaboratorySofteningPointMapper softeningPointMapper;

//    @Autowired
//    private LaboratoryDuctilityMapper ductilityMapper;

    @Autowired
    private LaboratoryPenetrationMapper penetrationMapper;

    @Autowired
    private MarshallStabilityMapper stabilityMapper;

    @Autowired
    private LaboratoryDeviceService deviceService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAsphalt(PlatformLaboratoryDataEntity entity) {
        QueryWrapper<AsphaltRequiresAndRefDto> query = new QueryWrapper<>();
        query.eq("ar.name",entity.getSampleName()).eq(StringUtils.isNotBlank(entity.getTestTemp()),"arr.temperature",entity.getTestTemp())
                .eq("arr.type",entity.getTestType());
        query.orderByAsc("arr.temperature");
        query.last("LIMIT 1");
        AsphaltRequiresAndRefDto asreq = requiresRefService.getRequiresByAspIdAndType(query);
        LaboratoryDeviceEntity device = getDeviceDeptId(entity.getEquipmentNumber());
        entity.setDeviceId(device.getCode());
        entity.setBaseCode(device.getBaseCode());
//        entity.setDeptPkid(device.getDeptPkid());
        if(ObjectUtils.isEmpty(asreq)){//直接入库
            addPlatformLaboratoryData(entity,CommonConstants.NO_DELETED);
        }else {
            String is_qualified = checkRequires(entity,asreq);
            entity.setIsQualified(is_qualified);
            entity.setMaxValue(asreq.getMaxValue());
            entity.setMinValue(asreq.getMinValue());
            if(StringUtils.isNotBlank(entity.getTestTemp())){
                entity.setTempature(new BigDecimal(entity.getTestTemp()));
            }
            addPlatformLaboratoryData(entity,entity.getIsQualified());
        }
    }

    @Override
    public void saveMarshall(PlatformLaboratoryDataEntity entity) {
        QueryWrapper<MarshallRequiresEntity> query = new QueryWrapper<>();
        query.eq("name",entity.getSampleName());
        MarshallRequiresEntity requiresMa = marshallRequiresService.getOne(query);
        LaboratoryDeviceEntity device = getDeviceDeptId(entity.getEquipmentNumber());
        entity.setDeviceId(device.getCode());
        entity.setBaseCode(device.getBaseCode());
//        entity.setDeptPkid(device.getDeptPkid());
        if(ObjectUtils.isEmpty(requiresMa)){//直接新增
            addPlatformLaboratoryData(entity,CommonConstants.NO_DELETED);
        }else{//更新或新增
            entity.setMaxFlow(requiresMa.getFlowMaxValue());
            entity.setMinFlow(requiresMa.getFlowMinValue());
            entity.setStabilityValue(requiresMa.getStabilityValue());
            addPlatformLaboratoryData(entity,checkMarshallRequires(entity,requiresMa));
        }
    }

    public void addPlatformLaboratoryData(PlatformLaboratoryDataEntity entity, String is_qualified){
        switch (entity.getTestType()){
            case CommonConstants.RHD : {
                QueryWrapper<LaboratorySofteningPointEntity> query = new QueryWrapper<>();
                query.eq("sample_no",entity.getSampleNo());
                LaboratorySofteningPointEntity sentity = softeningPointMapper.selectOne(query);
                if(ObjectUtils.isEmpty(sentity)){
                    LaboratorySofteningPointEntity spe = new LaboratorySofteningPointEntity();
                    BeanUtils.copyProperties(entity,spe);
                    spe.setIsQualified(is_qualified);
                    spe.setValue1(new BigDecimal(entity.getSoftenP()));
                    softeningPointMapper.insert(spe);
                }else{
                    sentity.setId(sentity.getId());
                    sentity.setIsQualified(is_qualified);
                    sentity = (LaboratorySofteningPointEntity)setValue(sentity,entity);
                    softeningPointMapper.updateById(sentity);
                }
            };break;
            case CommonConstants.YD : {
//                QueryWrapper<LaboratoryDuctilityEntity> query = new QueryWrapper<>();
//                query.eq("sample_no",entity.getSampleNo());
//                LaboratoryDuctilityEntity dentity = ductilityMapper.selectOne(query);
//                if(ObjectUtils.isEmpty(dentity)){
//                    LaboratoryDuctilityEntity spe = new LaboratoryDuctilityEntity();
//                    BeanUtils.copyProperties(entity,spe);
//                    spe.setAverage(entity.getAverageDuctility());
//                    spe.setIsQualified(is_qualified);
//                    spe.setValue1(new BigDecimal(entity.getDuctility()));
//                    ductilityMapper.insert(spe);
//                }else{
//                    dentity.setId(dentity.getId());
//                    dentity.setAverage(entity.getAverageDuctility());
//                    dentity.setIsQualified(is_qualified);
//                    dentity = (LaboratoryDuctilityEntity)setValue(dentity,entity);
//                    ductilityMapper.updateById(dentity);
//                }
            };break;
            case CommonConstants.ZRD : {
                QueryWrapper<LaboratoryPenetrationEntity> query = new QueryWrapper<>();
                query.eq("sample_no",entity.getSampleNo());
                LaboratoryPenetrationEntity pentity = penetrationMapper.selectOne(query);
                if(ObjectUtils.isEmpty(pentity)) {
                    LaboratoryPenetrationEntity spe = new LaboratoryPenetrationEntity();
                    BeanUtils.copyProperties(entity,spe);
                    spe.setIsQualified(is_qualified);
                    spe.setValue1(new BigDecimal(entity.getPenetration()));
                    penetrationMapper.insert(spe);
                }else{
                    pentity.setId(pentity.getId());
                    pentity.setIsQualified(is_qualified);
                    pentity = (LaboratoryPenetrationEntity)setValue(pentity,entity);
                    penetrationMapper.updateById(pentity);
                }
            };break;
            case CommonConstants.MARSHALL : {
                QueryWrapper<MarshallStabilityEntity> query = new QueryWrapper<>();
                query.eq("sample_no",entity.getSampleNo());
                MarshallStabilityEntity pentity = stabilityMapper.selectOne(query);
                if(ObjectUtils.isEmpty(pentity)) {
                    MarshallStabilityEntity spe = new MarshallStabilityEntity();
                    BeanUtils.copyProperties(entity,spe);
                    spe.setStabilityValue(entity.getStabilityValue());
                    spe.setIsQualified(is_qualified);
                    spe.setFlow1(new BigDecimal(entity.getFlow()));
                    spe.setStability1(new BigDecimal(entity.getStability()));
                    stabilityMapper.insert(spe);
                }else{
                    pentity.setId(pentity.getId());
                    pentity.setIsQualified(is_qualified);
                    pentity = (MarshallStabilityEntity)setMarshallValue(pentity,entity);
                    stabilityMapper.updateById(pentity);
                }
            };break;
        }
    }


    public Object setValue(Object t,PlatformLaboratoryDataEntity entity){
        try{
            Field ff = null;
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.VALUE1.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.VALUE1.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.VALUE2.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.VALUE2.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.VALUE3.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.VALUE3.getColumn());
            }
            ff.setAccessible(true);
            if(StringUtils.equals(entity.getTestType(),CommonConstants.RHD)){
                ReflectionUtils.setField(ff,t,new BigDecimal(entity.getSoftenP()));
            }if(StringUtils.equals(entity.getTestType(),CommonConstants.YD)){
                ReflectionUtils.setField(ff,t,new BigDecimal(entity.getDuctility()));
            }if(StringUtils.equals(entity.getTestType(),CommonConstants.ZRD)){
                ReflectionUtils.setField(ff,t,new BigDecimal(entity.getPenetration()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return t;
    }

    public Object setMarshallValue(Object t,PlatformLaboratoryDataEntity entity){
        try{
            Field ff = null;
            Field flow = null;
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL1.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL1.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW1.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL2.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL2.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW2.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL3.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL3.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW3.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL4.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL4.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW4.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL5.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL5.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW5.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL6.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL6.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW6.getColumn());
            }
            ff.setAccessible(true);
            flow.setAccessible(true);
            ReflectionUtils.setField(ff,t,new BigDecimal(entity.getStability()));
            ReflectionUtils.setField(flow,t,new BigDecimal(entity.getFlow()));
        }catch (Exception e){
            e.printStackTrace();
        }
        return t;
    }

    public String checkRequires(PlatformLaboratoryDataEntity entity,AsphaltRequiresAndRefDto reqires){
        try{
            String value = String.valueOf(entity.getAverage());
            if(StringUtils.equals("YD",entity.getTestType())){
                value = entity.getAverageDuctility();
            }
            String result = "1";
            if(StringUtils.isNotNull(reqires.getMaxValue()) && new BigDecimal(value).compareTo(reqires.getMaxValue())<=0){
                result =  "0";
            }
            if(new BigDecimal(value).compareTo(reqires.getMinValue()) >=0){
                result =  "0";
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "1";
    }
    public String checkMarshallRequires(PlatformLaboratoryDataEntity entity,MarshallRequiresEntity reqires){
        try{
            String value = String.valueOf(entity.getAverage());//流值平均值
            String stavalue = String.valueOf(entity.getStabilityAverage());//稳定值平均值
            String result = "1";
            if(StringUtils.isNotNull(reqires.getFlowMaxValue()) && new BigDecimal(stavalue).compareTo(reqires.getFlowMaxValue())<=0){
                    result =  "0";
            }
            if(new BigDecimal(value).compareTo(reqires.getFlowMinValue()) >=0){
                result =  "0";
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "1";
    }

    public LaboratoryDeviceEntity getDeviceDeptId(String equipmentNumber){
        QueryWrapper<LaboratoryDeviceEntity> query = new QueryWrapper<>();
        query.eq("deleted",CommonConstants.NO_DELETED)
                .eq("unique_code",equipmentNumber);
        LaboratoryDeviceEntity entity = deviceService.getOne(query);
        Assert.notNull(entity,"设备不存在！");
        return entity;
    }
}
